import axios from 'axios'
import store from '@/store'
import JSONBig from 'json-bigint'
import router from '@/router'

const request = axios.create({
  baseURL: 'http://toutiao.itheima.net',
  transformResponse: [function (data) {
    try {
      // 如果转换成功则返回转换的数据结果
      return JSONBig.parse(data)
    } catch (err) {
      // 如果转换失败，则包装为统一数据格式并返回
      return {
        data
      }
    }
  }]
})

request.interceptors.request.use(function (config) {
  const { user } = store.state
  if (user && user.token) {
    config.headers.Authorization = `Bearer ${user.token}`
  }
  // 注意：这里务必要返回 config 配置对象，否则请求就停在这里出不去了
  return config
}, function (err) {
  return Promise.reject(err)
})

request.interceptors.response.use(function (response) {
  return response
}, async function (err) {
  if (err.response && err.response.status === 401) {
    const user = store.state.user
    if (!user || !user.token) {
      router.push('/login')
      return
    }
    try {
      const res = await axios({
        method: 'PUT',
        url: 'http://toutiao.itheima.net/v1_0/authorizations',
        headers: {
          Authorization: `Bearer ${user.refresh_token}`
        }
      })
      console.log(res)
      store.commit('setUser', {
        token: res.data.data.token,
        refresh_token: user.refresh_token
      })
      return request(err.config)
    } catch (err) {
      console.log(err)
      router.push('/login')
    }
  }
  return Promise.reject(err)
})

export default request
